package org.ling.xuan.action;

import cn.hutool.core.util.StrUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.stream.Collectors;

public class LxRemoveEnter extends AnAction {
    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        Editor editor = e.getDataContext().getData(com.intellij.openapi.actionSystem.PlatformDataKeys.EDITOR);
        if (editor != null) {
            String selectedText = editor.getSelectionModel().getSelectedText();
            if (StrUtil.isNotBlank(selectedText)) {
                List<String> ss = StrUtil.split(selectedText,"\n");
                ss = ss.stream().map(String::trim).filter(StrUtil::isNotBlank).collect(Collectors.toList());
                if (!editor.getDocument().isWritable()) {
                    editor.getDocument().setReadOnly(false);
                }
                write(e.getProject(), editor,StrUtil.join("",ss));
            } else {
                Messages.showMessageDialog(
                        "No text selected!",
                        "Remove Newlines",
                        Messages.getInformationIcon()
                );
            }
        }
    }

    @Override
    public void update(AnActionEvent e) {
        Editor editor = e.getDataContext().getData(com.intellij.openapi.actionSystem.PlatformDataKeys.EDITOR);
        e.getPresentation().setEnabledAndVisible(editor != null && editor.getSelectionModel().hasSelection());
    }

    private void write(Project project, Editor editor, String s) {
        if (project != null && editor != null) {
            WriteCommandAction.runWriteCommandAction(project, () -> {
                editor.getDocument().replaceString(
                        editor.getSelectionModel().getSelectionStart(),
                        editor.getSelectionModel().getSelectionEnd(),
                        s
                );
            });
        }
    }
}
